var tmpObj;
var shuju=1;
var ctag="0";

var rolechooser = "1001,1002,1003,1004,1005,1007,1008,1009,1010,1014,1015,1016";//这里默认带班领导 rolechooser（角色的ID）传进来是为了过滤可选的角色。

$(document).ready(function() {		
	var default_role = "1006";//默认角色
	findAllDeptType();
	
	
	$('.slt').click(function() {
		$("#deptul").empty();
		findAllDeptType();
		
		$("#selDepts").empty();
		$("#subDepts").empty();
		if($(this).attr("id")!=undefined&&$(this).attr("id")!="")//判断元素的id是否有值
	{
			var tmp_num=parseInt($(this).attr("id"));
			var tmp_str=parseInt($(this).attr("id")).toString();// 判断是否是角色的ID
			if(tmp_str!="NaN"&&tmp_num>=1000&&tmp_num<=1020)
		{
			default_role=$(this).attr("id");//如果角色是数字的话赋值给d_r
			$("#roleList option[value="+default_role+"]").attr("selected",true);//选中角色
			$.ajax({  //对应 default_role左边框的人员
		         type: "post",
		         url: "admin/queryUser_query.action",
		         data:{
			     "queryOption['URole']": default_role
		         },
		         success: function(data){
		        showDialogRole(data);
			
		     }
	         });//ajax
//			alert("selDeptAndRole.js1");
		}else{ //如果$(this).attr("id")为string
				$("#roleList option[value='noselect']").attr("selected",true);//选择 “请选择”
			 };
			
	}else{ //如果$(this).attr("id")为空
				$("#roleList option[value='noselect']").attr("selected",true);//选择 “请选择”
		 };
		
		tmpObj=$(this);	
		$("#leaderChooseWindow").dialog("open");
		//$("#deptChooseWindow1").dialog("open");
	});
	
	$('.del').click(function() {
		$(this).prev().val("选择");
		$(this).prev().prev().prev().text("");
		$(this).prev().prev().text("");
	});

	$("#leaderChooseWindow").dialog({
		autoOpen : false,
		minWidth : 650,
		modal : true,
		title : '选择人员',
		close : function() {
			ctag="0";
			return false;
		}
	});

	//取消通知带班领导
	$("#cancelNotify").click(function(){
		$("#deptChooseWindow").dialog('close');
		window.location.href="/ag/work/event_query_start.jsp";
	});
	//确定选择人员
	$("#selOk").click(function(){
		if(ctag=="1"){
			if(confirm("确定呈批给"+$("#selDepts option").get(0).text+"？"))
			{
			//alert("确定");
			ctag="0";
			savePropose($("#selDepts option").get(0).value);
			//alert("记录");
			
			//saveToFomalPropose();
			}
			return;
		}
		tmpObj.prev().prev().text($("#selDepts option").get(0).text);
		tmpObj.prev().text($("#selDepts option").get(0).value);
		tmpObj.val("修改");
		$("#leaderChooseWindow").dialog('close');
	});
	/*
	 * 存储到正式 的呈批表
	 */
	function saveToFomalPropose(){
		var a=$('#tbUserByPCommander1').text();
		var b=$('#tbUserByPViceCommander1').text();
		var c=$('#tbUserByPTeamLeader1').text();
		var d=$('#tbUserDeptByPImplementPlan').text();
		var e=$('#tbUserDeptByPAssistDept1').text();
		saveAdmin(a,b,c,d,e);
	}
	
function saveAdmin(a,b,c,d,e){
    var EId = getCookie(eventId);
    var url = 'work2/LZMReport_saveAdmin.action';
    var params = {
        'proposes.tbUserByPViceCommander.UId': b,
        'proposes.tbUserByPTeamLeader.UId': c,
        'proposes.tbUserByPCommander.UId': a,
        'proposes.tbEvent.EId': EId,
		//下面是部门
		'proposes.e': d,
		'proposes.tbUserDeptByPAssistDept.udId': e
    };
    jQuery.post(url, params, saveAdminRstZRT, 'json');
}
	
/**
 * 作增加呈批回调函数
 */
function saveAdminRstZRT(data){
	if (data.ajaxRst == "success") {
		window.location.href="reportTable.jsp?reportTag=succ";
	}else{
		alert("服务器异常！");
	}	
}

	//取消选择人员
	$("#selCancel").click(function(){
		ctag="0";
		//alert(ctag);
		$("#leaderChooseWindow").dialog('close');
	});
	// 测试弹出通知带班领导的选择窗体
	$("#dept").click(function(){
//		$("#deptArea").show();
		$("#roleArea").hide();
		$("#subDepts").empty();
		$("#subDeptstd").hide();
		$("#deptultd").show();
		$("#addDept").hide();
	});
	$("#role").click(function(){
//		$("#deptArea").hide();
		$("#roleArea").show();
		$("#subDeptstd").show();
		$("#subDepts").empty();
		$("#deptultd").hide();
		$("#addDept").show();
		
		
		//添加当前选择的角色的人员到左边的select(id=subDepts)
		var q_URole = $("#roleList option:selected").val();
		if(q_URole=="noselect"){}
		else{
		$.ajax({
			type : "post",
			url : "admin/queryUser_query.action",
			data : {"queryOption['URole']":q_URole},
			success : function(data){
//				$("#subDepts").empty();
//				$.each(data.pageUtil.list,function(i,n){
//					$("#subDepts").append("<option value="+n.UId+">"+n.UName+"</option>");
//				});
				showDialogRole(data);
				
				
			}
		});//ajax
//		alert("selDeptAndRole.js2");
		}
		
		
		
	});
	// 指派部门的窗体上两个按钮的响应函数 addDept 和 delDept
	$("#addDept").click(function() {
		if ($("#subDepts option:selected").length > 0) {
			$("#subDepts option:selected").each(function() {
				var strHtml="";
				var udId = $(this).val();
				var udName = $(this).text();
				if($("#selDepts option").length == 1){
					//alert("只能选择一个人！");
					return ;
				}
				if ($("#selDepts option").length > 0 ) { //
					var t = true;
					$("#selDepts option").each(function(){
						if(udId == $(this).val()){ 
							t = false;
						}
					})
					if(t){
						strHtml+="<option class='class1' name='selDepts' selected value='" + udId + "'>"
							+ udName + "</option>";
						//$("#leader").empty().append(udName).css("font-weight","bold");
						//$("#leaderId").empty().append(udId);
					}
				}else{
					strHtml+="<option class='class1' name='selDepts' selected value='" + udId + "'>"
						+ udName + "</option>";
					//$("#leader").empty().append(udName).css("color","#960").css("font-weight","bold");
					//$("#leaderId").empty().append(udId);
				}
				$("#selDepts").append(strHtml);
			})
		}
	});

	$("#delDept").click(function() {
		if ($("#selDepts option:selected").length > 0) {
			$("#selDepts option:selected").each(function() {
		//		$("#leader").empty().append("没有选择带班领导").css("color","red").css("font-weight","bold");
		//		$("#leaderId").empty();
				$(this).remove();
			})
		}
	});
	
	
	
	$("#deptType").change(function() {
		var dtId = $("#deptType option:selected").val();
		//alert("sdfsdfsdf");
		//alert(dtId);
		$.ajax({
  			type: "post",
  			data:{"dtId":dtId},
 			url: "/ag/admin/userDept_findUserDeptByDtId.action",
  			success:function(data){
  				$("#q_UDept").empty();
  				$("#q_UDept").append("<option value='0'>请选择</option>");
  				$.each(data.userDepts,function(i,n){
  					$("#q_UDept").append("<option value="+n.udId+">"+n.udName+"</option>");
				});
  			}
  		});
	});
	$("#q_UDept").change(function() {
		var UDept = $("#q_UDept option:selected").val();
		$.ajax({
			type : "post",
			url : "/ag/admin/queryUser_query.action",
			data : {"queryOption['UDept']":UDept},
			success : function(data){
				
				showDialogRole(data);
			}
		});
//		alert("selDeptAndRole.js");
	});
	$("#roleList").change(function() {
		var q_URole = $("#roleList option:selected").val();
		$.ajax({
			type : "post",
			url : "/ag/admin/queryUser_query.action",
			data : {"queryOption['URole']":q_URole},
			success : function(data){
//				$("#subDepts").empty();
//				$.each(data.pageUtil.list,function(i,n){
//					$("#subDepts").append("<option value="+n.UId+">"+n.UName+"</option>");
//				});
				showDialogRole(data);
			}
		});
//		alert("selDeptAndRole.js3");
	});
	
	/**
	 * 2011年6月26号修改
	 */
	$("#selDepts").dblclick(function(){
		removeSelected();
	});
	
	$("#subDepts").dblclick(function(){
		
		moveRole();
	});
	/**
	 * 2011年6月26号修改
	 */
	
});



/**
 * 添加人员结点——方法
 * @param users
 * @param ulId
 * @return
 */
function setPeople(users,ulId){
	var idOfUl = "#" + $.trim(ulId);
	$.each(users,function(i,n){
		shuju++;
		ckBoxId="ckbox"+shuju;
		$(idOfUl).append("<li>"+"<input type=\"checkbox\" id=\""+ckBoxId+"\"/>"+"<label for="+ckBoxId+">"+n.UName+"</label>"+"</li>");
		var ckBox_id = "#" + $.trim(ckBoxId);
		$(ckBox_id).click(function() {
		if($(ckBox_id).attr("checked")==true){//如果是打钩的话，增加到右边的select
		if($("#selDepts option:selected").text()==""){//如果右边为空允许添加
					$("#selDepts").empty();
				setTimeout(function(){
					$("#selDepts").append("<option class='class1' name='selDepts' selected value='" + n.UId + "'>"
							+ n.UName + "</option>");
				},100);}
				else{//右边不为空则不能添加。
					$(this).attr("checked",false);
					alert("只能选择一个人员");
				}
			}
			else{//取消打钩，清楚右边的框
				$("#selDepts").empty();
			}
		});
	});
}

function chgIcon(spanId){
	var span_id = "#" + $.trim(spanId);
	var imgsrc= $(span_id).children("img").attr("src");
	if(imgsrc=="/ag/wzp/images/jiahao.gif") {
		$(span_id).children("img").attr("src","/ag/wzp/images/jianhao.gif");
	}else{
		$(span_id).children("img").attr("src","/ag/wzp/images/jiahao.gif");}
}

function findAllDeptType(){
	var extern = 0;
	$.ajax({     //ajax
		type: "post",
		url: "/ag/admin/userDept_findAllDeptType.action",
		success:function(data){
		$("#deptul").empty();
		$.each(data.deptTypes,function(i,n){
//			alert(n.dtName);
		 extern++; 
		 var temp = "span_id"+extern;
		var temp2 = "ul_id"+extern;
		if(n.dtId=="0001"||n.dtId=="0003"||n.dtId=="0002"){}
		else{
		$("#deptul").append("<li>"+"<span style=\"cursor: pointer;\" id="+temp+">"+"<img src=\"/ag/wzp/images/jiahao.gif\">"+n.dtName+"</span>"+"<ul style=\"list-style:none\" id="+temp2+">"+"</ul>"+"</li>");
		}
		var span_id = "#" + $.trim(temp);
		var ul_id = "#" + $.trim(temp2);
		$(span_id).children("img").attr("src","/ag/wzp/images/jiahao.gif");
		$(span_id).click(function() {
			chgIcon(temp);
			var deptTypeId = n.dtId;
//			alert(deptTypeId);
			$.ajax({     //ajax
	  			type: "post",
	  			data:{"deptTypeId":deptTypeId},
	 			url: "/ag/lwc/findFirstLevel_FindfDeptAction.action",
	  			success:function(data){
	  				if($(ul_id).text()!=""){
		  				$(ul_id).empty();
		  				$("#selDepts").empty();
		  			}else{
//		  			     alert(data.depts);
		  			     if(data.users!=null){
//		  			     alert(data.users);
		  			     setPeople(data.users,temp2);//tmpe2为ul 的id
		  			     }
		  				$.each(data.depts,function(i,n){
		  					extern++;
		  				var temp3 = "span2_id"+extern;
  				     	var temp4 = "ul2_id"+extern;
	  					$(ul_id).append("<li>"+"<span style=\"cursor: pointer;\" id="+temp3+">"+"<img src=\"/ag/wzp/images/jiahao.gif\">"+n.udName+"</span>"+"<ul style=\"list-style:none\" id="+temp4+">"+"</ul>"+"</li>");
	  					var span2_id = "#" + $.trim(temp3);
	  					var ul2_id = "#" + $.trim(temp4);
	  					$(span2_id).children("img").attr("src","/ag/wzp/images/jiahao.gif");
	  					$(span2_id).click(function() {
	  						chgIcon(temp3);
	  						var udid_1 = n.udId;
	  						$.ajax({
	  							type : "post",
	  				  			data:{"udid":udid_1},
	  				 			url: "/ag/lwc/nextLevel_FindfDeptAction.action",
	  				  			success:function(data){
	  				  			if($(ul2_id).text()!=""){
	  				  				$(ul2_id).empty();
	  				  				$("#selDepts").empty();
	  				  			}else{
//	  				  			alert(data.depts);
	  				  		if(data.users!=null){
//	  			  			     alert(data.users);
	  			  			  setPeople(data.users,temp4);//tmpe2为ul 的id
	  				  		}
	  				  		$.each(data.depts,function(i,n){
	  				  			extern++;
	  				  		var temp5 = "span3_id"+extern;
	  				     	var temp6 = "ul3_id"+extern;
	  				     	$(ul2_id).append("<li>"+"<span style=\"cursor: pointer;\" id="+temp5+">"+"<img src=\"/ag/wzp/images/jiahao.gif\">"+n.udName+"</span>"+"<ul style=\"list-style:none\" id="+temp6+">"+"</ul>"+"</li>");
	  				     	var span3_id = "#" + $.trim(temp5);
		  					var ul3_id = "#" + $.trim(temp6);
		  					$(span3_id).children("img").attr("src","/ag/wzp/images/jiahao.gif");
		  					$(span3_id).click(function() {
		  						chgIcon(temp5);
		  					
		  						var udid_2 = n.udId;
		  						$.ajax({
		  							type : "post",
		  				  			data:{"udid":udid_2},
		  				 			url: "/ag/lwc/nextLevel_FindfDeptAction.action",
		  				  			success:function(data){
		  				  			if($(ul3_id).text()!=""){
		  				  				$(ul3_id).empty();
		  				  				$("#selDepts").empty();
		  				  			}else{
		  				  				if(data.depts!=null){
//		  				  			alert(data.depts);
		  				  				}
		  				  		if(data.users!=null){
//		  			  			     alert(data.users);
		  			  			  setPeople(data.users,temp6);//tmpe6为ul 的id
		  				  		}
		  				  			}
		  				  			}
		  				  			});
		  						
		  					});
	  				  		});
	  				  				
	  				  			}
	  				  				
	  				  				
	  				  			}
	  							
	  						});

	  						
	  					});
		  					
		  				});
		  				}
			}
		});
			
			
		});
		
		});
		
	}
	});
	
}


	

	
	

	
//获取所有角色 修改：获取特定角色ID的角色  放进到SELECT（id=rolelist）里面。
function findAllRole(rolechooser, default_role){//default_role默认角色id号
	//alert("default_role"+default_role);
	//alert(typeof(default_role));
	var tarray = rolechooser.split(",");//rolechooser（角色的ID）传进来是为了过滤可选的角色。
	$.ajax({
		type: "post",
		url: "admin/Role_findAllRole.action",//因为com.ag.admin.action.RoleAction的controller配的是RoleAction
		success: function(data){
			$("#roleList").empty();
			$("<option value='noselect'>请选择</option>").appendTo("#roleList");
			$.each(data.roles, function(i, n){
				//alert(typeof(n.RId));
				for (var i = 0; i < tarray.length; i++) {
					if (tarray[i] == n.RId) {
						if (parseInt(n.RId) == default_role) {
							//alert(n.RName);
							$("<option  selected value=" + n.RId + ">" + n.RName + "</option>").appendTo("#roleList");
						}
						else {
							//alert(n.RName+"2");
							$("<option value=" + n.RId + ">" + n.RName + "</option>").appendTo("#roleList");
						}
					}
					//alert("ggggggggggg");
				}
			});
		}
	});//ajax
	//默认选择的角色，把数据直接放到左边的select（ID=subDepts）里面
	$.ajax({
		type: "post",
		url: "admin/queryUser_query.action",
		data: {
			"queryOption['URole']": default_role
		},
		success: function(data){
			showDialogRole(data);
		}
	});//ajax
	
}
	function showMessage(){
		$("#dialog").dialog("destroy");
		$("#dialog-message").dialog({
			height:150,
			width: 280,
			modal: true,
			resizable: false
		});
	}
	
	
	/**
	 * 2011年6月26号修改
	 */
	//要有data
	function showDialogRole(data){
		$("#subDepts").empty();
		$.each(data.pageUtil.list, function(i, n){
			$("#subDepts").append("<option class='soption' value=" + n.UId + ">" + n.UName + "</option>");
		});
		
	}
	
	
	/**
	 * 把选中的移过去
	 * @return
	 */
	function moveRole(){
		if ($("#subDepts option:selected").length > 0) {
			$("#subDepts option:selected").each(function() {
				var strHtml="";
				var udId = $(this).val();
				var udName = $(this).text();
				if($("#selDepts option").length == 1){
					//alert("只能选择一个人！");
					return ;
				}
				if ($("#selDepts option").length > 0 ) { //
					var t = true;
					$("#selDepts option").each(function(){
						if(udId == $(this).val()){ 
							t = false;
						}
					})
					if(t){
						strHtml+="<option class='class1' name='selDepts' selected value='" + udId + "'>"
							+ udName + "</option>";
						//$("#leader").empty().append(udName).css("font-weight","bold");
						//$("#leaderId").empty().append(udId);
					}
				}else{
					strHtml+="<option class='class1' name='selDepts' selected value='" + udId + "'>"
						+ udName + "</option>";
					//$("#leader").empty().append(udName).css("color","#960").css("font-weight","bold");
					//$("#leaderId").empty().append(udId);
				}
				$("#selDepts").append(strHtml);
			})
		}
	}
	
	/**
	 * 把已选中的移除
	 * @return
	 */
	function removeSelected(){
		if ($("#selDepts option:selected").length > 0) {
			$("#selDepts option:selected").each(function() {
				$(this).remove();
			})
		}
	}
	
	/**
	 * 2011年6月26号修改
	 */
